package org.example.service.Impl;

import lombok.extern.slf4j.Slf4j;
import org.example.exception.BusinessException;
import org.example.mapper.UserMapper;
import org.example.pojo.LoginInfo;
import org.example.pojo.User;
import org.example.service.UserService;
import org.example.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;

    /*
    * 实现登录方法
    * */
    @Override
    public LoginInfo login(User user) {
        User userLogin = userMapper.getUsernameAndPassword(user);
        if (userLogin != null)
        {
            // 1.生成token
            Map<String, Object> claims = new HashMap<>();
            claims.put("id", userLogin.getId());
            claims.put("username", userLogin.getUsername());
            String token = JwtUtils.generateJwt(claims);

            log.info("用户登录：{}", userLogin);
            return new LoginInfo(userLogin.getId(), userLogin.getUsername(), userLogin.getPassword(), token);
        }
        return null;
    }

    /*
    * 获取用户信息
    * */
    @Override
    public User getUserInfo(String token) {
        // 1.通过token获取用户信息
        Map<String, Object> claims = JwtUtils.parseJwt(token);
        Integer id = (Integer) claims.get("id");
        String username = (String) claims.get("username");
        if (id == null || username == null) {
            throw new BusinessException("token无效");
        }
        // 2.通过用户信息查询用户
        User user = userMapper.findByUsername(username);
        if (user == null) {
            throw new BusinessException("用户不存在");
        }
        return user;
    }


    /*
    * 修改密码
    * */
    @Override
    public void updatePassword(String oldPassword, String newPassword) {
        // 1.通过原本的密码查询用户
        User user = userMapper.getUserByPassword(oldPassword);
        if (user == null) {
            throw new BusinessException("密码错误");
        }
        if (newPassword.equals(oldPassword)) {
            throw new BusinessException("新密码不能与旧密码相同");
        }

        // 2.修改密码
        log.info("修改密码：{}", user);
        userMapper.updatePassword(user.getId(), newPassword);
        return;
    }
}
